# dbhelp2html.awk
# converts D'Bridge dbhelp.txt to HTML
#
# by Lars Kellogg-Stedman 1:322/761

# Stuff to skip outright.
/^!/ {next}
/^\/\*/ {next}
/^\*\// {next}

# Recognize section headings.  This puts the current section name
# in sec_name and section number in sec_num.
/^#/ {
	# If there's an open <p> tag, close it.
	if (in_p) {
		print "</p>"
		in_p=0
	}

	# If there's an open <pre> tag, close it.
	if (in_pre) {
		print "</pre>"
		in_pre=0
	}

	sec_name = $2
	sec_num = $3

	gsub("_", " ", sec_name);

	start_sec = 1
}

# Skip the table of contents (we generate our own)
sec_name ~ "^TABLE OF CONTENTS" { next }

# Skip the title section.
sec_name ~ "^TITLE" { next }

# Print section headings.
start_sec {
	# Show progress on stderr.
	if (sec_num)
		printf "[%s] %s\n", sec_num, sec_name >> "/dev/stderr"

	if (! sec_num)
		printf "<h4>%s</h4>\n", sec_name
	else if (sec_num ~ /\.00/)
		printf "<h2 id=\"%s\">%s %s</h2>\n", sec_num, sec_num, sec_name
	else
		printf "<h3 id=\"%s\">%s %s</h3>\n", sec_num, sec_num, sec_name

	start_sec = 0
	next;
}

# Basic HTML entity substitution.
{
	gsub("&", "\\&amp;")
	gsub("<", "\\&lt;")

	$0 = gensub(/([^]+)/, "<strong>\\1</strong>", "g")
	$0 = gensub(/([^]+)/, "<em>\\1</em>", "g")
	$0 = gensub(/([^]+)/, "<strong>\\1</strong>", "g")

	gsub("", "")
}

# Handle normal and preformatted text (CTRL-T and CTRL-P).
! in_pre && /^/ {
	in_pre=1
	print "<pre>"
}

/^/ {gsub("", "")}

in_pre && /^/ {
	in_pre=0
	print "</pre>"
}

/^/ {
	if (! in_p) {
		print "<p>"
		in_p=1
	}

	gsub("", "")
}

in_pre {
	print
	next
}

# Recognize paragraphs.
/^$/ {
	if (in_p) {
		print "</p>"
		in_p=0
	}

	blank=1
	next
}

blank && ! /^$/ {
	blank=0
	print "<p>"
	in_p=1
}

# This doesn't actually work.  I think HTMLDOC is commenting
# out the <style> tag.
## Try to make text * LIKE THIS * a little prettier.
#/\* [[:upper:]]+ \*/ {
#	$0 = gensub(/\* ([[:upper:]]+) \*/,
#	       "* <span style=\"color: red\">\\1</span> *",
#	       "",
#	       $0)
#}


# Print current line (with any modifications made above).
{print}

